package collector

import (
	"context"
	"github.com/go-kit/kit/log"
	"github.com/go-redis/redis/v8"
	"github.com/prometheus/client_golang/prometheus"
	"strconv"
	"strings"
)

// Scraper is minimal interface that let's you add new prometheus metrics to redis_exporter.
type Scraper interface {
	// Name of the Scraper. Should be unique.
	Name() string

	// Help describes the role of the Scraper.
	// Example: "info replication"
	Help() string

	// Version of Redis from which scraper is available.
	Version() float64

	// Scrape collects data from redis client and sends it over channel as prometheus metric.
	Scrape(ctx context.Context, client *redis.Client, ch chan<- prometheus.Metric, logger log.Logger) error
}

func formatStrReply(reply string, sep string, kvSep string) map[string]string {
	data := make(map[string]string)

	// 处理响应字符串
	arr := strings.Split(reply, sep)
	for _, field := range arr {
		kv := strings.Split(field, kvSep)
		if len(kv) > 1 {
			data[kv[0]] = kv[1]
		}
	}

	return data
}

func infos(client *redis.Client, sections ...string) (map[string]string, error) {
	data := make(map[string]string)

	for _, section := range sections {
		reply, err := client.Info(context.TODO(), section).Result()
		if err != nil {
			return nil, err
		}
		tmp := formatStrReply(reply, "\r\n", ":")
		for k, v := range tmp {
			data[k] = v
		}
	}

	return data, nil
}

func valueOf(data map[string]string, key string) float64 {
	val, err := strconv.ParseFloat(data[key], 64)
	if err != nil {
		val = 0
	}
	return val
}
